import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Container,
  Paper,
  Tabs,
  Tab,
  CssBaseline,
  CircularProgress,
  Alert,
  Snackbar
} from '@mui/material';
import NavBar from '../components/Navbar';
import { useNavigate, Link, useLocation } from 'react-router-dom';
import { navigationItems } from '../App';
import { instance } from '../axios';
import Admin from '../components/Admin';

function AdminPage() {
  const [isAdmin, setIsAdmin] = useState(false); // 默认设置为false，需要验证权限
  const [loading, setLoading] = useState(true); // 默认设置为true，显示加载中
  const [error, setError] = useState(null);
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    // 检查用户是否是管理员
    const userToken = localStorage.getItem('token');
    if (!userToken) {
      navigate('/login');
      return;
    }

    // 获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('user') || '{}');

    // 检查用户角色
    if (userInfo.role === 'admin') {
      setIsAdmin(true);
      setLoading(false);
    } else {
      // 调用后端API验证用户是否有管理员权限
      const checkAdminPermission = async () => {
        try {
          // 调用管理员接口，如果成功返回则有权限，如果返回401或403则无权限
          await instance.get('/admin/users');
          setIsAdmin(true);
        } catch (error) {
          console.error('用户没有管理员权限:', error);
          setIsAdmin(false);
          setError('您没有管理员权限。只有管理员用户才能访问此页面。');
        } finally {
          setLoading(false);
        }
      };

      checkAdminPermission();
    }
  }, [navigate]);


  if (loading) {
    return (
      <Box>
        <NavBar />
        <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '70vh' }}>
          <CircularProgress sx={{ color: '#d81b60' }} />
        </Box>
      </Box>
    );
  }

  return (
    <div className="App" style={{ backgroundColor: '#fefaff', minHeight: '100vh' }}>
      <CssBaseline />
      <NavBar />
      
      <Container
        maxWidth="false"
        sx={{
          backdropFilter: 'blur(4px)',
          backgroundColor: 'rgba(255,255,255,0.6)',
          borderRadius: 3,
          p: 2,
          mt: 3,
        }}
      >
        <Box sx={{ maxWidth: '1400px', mx: 'auto' }}>
          <Tabs
            value={location.pathname}
            indicatorColor="secondary"
            textColor="secondary"
            variant="scrollable"
            scrollButtons="auto"
            sx={{
              borderBottom: '2px solid #f3e5f5',
              mb: 2,
              '& .MuiTab-root': {
                transition: 'all 0.3s ease-in-out',
              },
              '& .Mui-selected': {
                color: '#8e24aa',
                fontWeight: 'bold',
              },
              '& .MuiTabs-indicator': {
                height: 3,
                backgroundColor: '#ce93d8',
                borderRadius: 2,
              }
            }}
          >
            {navigationItems
              .filter(item => !item.adminOnly || (isAdmin))
              .map((item) => (
                <Tab
                  key={item.path}
                  label={item.label}
                  value={item.path}
                  component={Link}
                  to={item.path}
                  sx={{
                    minWidth: 100,
                    borderRadius: 2,
                    mx: 0.5,
                    transition: 'all 0.3s',
                    color: '#8e24aa',
                    '&:hover': {
                      backgroundColor: '#ffe0f0',
                      color: '#d81b60',
                    },
                    '&.Mui-selected': {
                      fontWeight: 'bold',
                      color: '#d81b60',
                      backgroundColor: '#fff0f5',
                    },
                  }}
                />
            ))}
          </Tabs>
        </Box>
      </Container>
      
      <Container maxWidth="false" sx={{ paddingTop: 3 }}>
        <Box sx={{ maxWidth: '1400px', mx: 'auto' }}>
          {isAdmin ? (
            <Paper elevation={3} sx={{
              p: 3,
              borderRadius: 3,
              background: 'linear-gradient(135deg, #fff9fa 0%, #fef4ff 100%)',
              boxShadow: '0 4px 20px rgba(200, 100, 255, 0.1)',
            }}>
              <Typography
                variant="h4"
                sx={{
                  mb: 3,
                  color: '#8e24aa',
                  fontWeight: 'bold',
                  textAlign: 'center',
                  textShadow: '1px 1px 3px rgba(0,0,0,0.1)'
                }}
              >
                管理员控制台
              </Typography>
              <Admin />
            </Paper>
          ) : (
            <Alert
              severity="error"
              variant="filled"
              sx={{
                py: 2,
                borderRadius: 2,
                boxShadow: '0 4px 8px rgba(211, 47, 47, 0.2)'
              }}
            >
              {error || '您没有权限访问管理控制台。只有管理员用户才能访问此页面。'}
            </Alert>
          )}
        </Box>
      </Container>
    </div>
  );
}

export default AdminPage;

